package com.inspur.gs.sbssdl.database.spqm.spqm.back.bizactions;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.bef.api.lcp.IStandardLcp;
import com.inspur.edp.bef.core.LcpUtil;
import com.inspur.edp.caf.db.dbaccess.DbParameter;
import com.inspur.edp.caf.db.dbaccess.DynamicResultRow;
import com.inspur.edp.caf.db.dbaccess.IDbParameter;
import com.inspur.edp.cef.api.message.*;
import com.inspur.edp.bef.api.action.determination.*;
import com.inspur.edp.bef.api.action.validation.*;
import com.inspur.edp.cef.entity.changeset.*;
import com.inspur.edp.bef.api.be.*;
import com.inspur.edp.bef.api.action.VoidActionResult;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IEntityDataCollection;
import com.inspur.edp.cef.entity.entity.IValuesContainer;
import com.inspur.edp.qdp.bql.api.IBqlExecuter;
import com.inspur.edp.qdp.bql.api.OptionType;
import com.inspur.edp.svc.document.storage.api.DocStorageService;
import com.inspur.edp.svc.document.storage.entity.GspDocContent;
import com.inspur.edp.svc.document.storage.entity.GspDocMetadata;
import com.inspur.edp.svc.document.storage.entity.GspDocOperatingModes;
import com.inspur.gs.sbssdl.database.spqm.spqm.back.util.HttpUtil;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rpc.client.RpcClassHolder;
import io.iec.edp.caf.runtime.config.BqlBeanUtil;

import java.io.File;
import java.time.OffsetDateTime;
import java.util.*;

public class sbssRyqmqyqmMgrAction extends AbstractManagerAction<VoidActionResult> {
	private String id;
	private String mxId;
	public sbssRyqmqyqmMgrAction(IBEManagerContext managerContext, String id,
			String mxId) {
		super(managerContext);
		this.id = id;
		this.mxId = mxId;
	}

	private String ryqmCfg = "com.inspur.gs.sbssdl.database.spqm.spqm.back.sbssRyqm";
	private IBqlExecuter bqlExecuter;
	private final ObjectMapper objectMapper = new ObjectMapper();

	@Override
	public  void execute() {
		bqlExecuter = BqlBeanUtil.getAppCtx().getBean(IBqlExecuter.class);
		bqlExecuter.getOptions().setOptionType(OptionType.ExecuteSql);
		RpcClassHolder rpcClassHolder = SpringBeanUtils.getBean(RpcClassHolder.class);
		DocStorageService docStorage = rpcClassHolder.getRpcClass(DocStorageService.class);

		String attachmentId = "";
		String fileName = "";
		String fileSize = "";

		IStandardLcp lcp = LcpUtil.getLcp(ryqmCfg);
		IEntityData data = lcp.retrieve(id).getData();

		IValuesContainer xtyh = (IValuesContainer) data.getValue("xtyh");

		String userId = xtyh.getValue("xtyh").toString();
		String userName = xtyh.getValue("xtyh_name").toString();

		ModifyChangeDetail dataModify = new ModifyChangeDetail(id);
		IEntityDataCollection fj = data.getChilds().get("fj");
		for(IEntityData fjData : fj){
			String fjDataID = fjData.getID();
			if ((Boolean) fjData.getValue("isActive") && !fjDataID.equals(mxId)) {
				ModifyChangeDetail fjModify = new ModifyChangeDetail(fjDataID);
				fjModify.setItem("isActive",false);
				dataModify.addChildChangeSet("fj",fjModify);
			}else if (fjDataID.equals(mxId)) {
				ModifyChangeDetail fjModify = new ModifyChangeDetail(fjDataID);
				fjModify.setItem("isActive",true);
				dataModify.addChildChangeSet("fj",fjModify);

				Object value =  fjData.getValue("fjinfo");
				if (value != null) {
					attachmentId = ((IValuesContainer) value).getValue("AttachmentId").toString();
					fileName = ((IValuesContainer) value).getValue("FileName").toString();
					fileSize = ((IValuesContainer) value).getValue("FileSize").toString();
				}
			}
		}

		GspDocContent docContent = docStorage.getDocContent(attachmentId, "user-sign");
		byte[] fileContent = docContent.getFileContent();

		// String attIdObj = getAttIdObj(userId);

		String rooId = "taskcentersignature";
		GspDocMetadata metadata = new GspDocMetadata(rooId);
		metadata.setFileName(fileName);
		metadata.setDocType("png");
		metadata.setDocSize(fileSize);
		metadata.setLastModifiedTime(OffsetDateTime.now());

//		if (attIdObj == null) {
//			// 新增签名
//			docStorage.uploadDoc(userId, metadata, fileContent, GspDocOperatingModes.Formal);
//		}else {
//			// 更新签名
//			docStorage.updateDoc(attIdObj,fileContent,GspDocOperatingModes.Formal,rooId);
//		}

		docStorage.uploadDoc(userId, metadata, fileContent, GspDocOperatingModes.Formal);

		lcp.modify(dataModify);
		lcp.save();
	}

	// 查询最新的签名
	private String getAttIdObj(String userId) {
		List<IDbParameter> params = new ArrayList<>();
		String sql = "SELECT meta.METADATAID as attid " +
				"FROM GSPDOCMETADIRRELATION meta join GSPDOCDIRECTORY dir on meta.DIRECTORYID = dir.id join GSPDOCMETADATA data on meta.METADATAID = data.ID join GSPDOCDBCONTENT db on db.METADATAID = data.ID\n" +
				"where dir.ROOTID like 'taskcentersignature' " +
				"  and dir.code = :userId \n" +
				"order by db.LASTMODIFIEDTIME desc";
		params.add(new DbParameter("userId",userId));
		List<DynamicResultRow> dynamicResultRows = bqlExecuter.executeSelectStatement(sql, new ArrayList<>(),params.toArray(new IDbParameter[]{}));
		if (!dynamicResultRows.isEmpty()) {
			return dynamicResultRows.get(0).get("attid").toString();
		}else {
			return null;
		}
	}


	private IBusinessEntity getEntity(String dataId) {
		return (IBusinessEntity)super.getBEManagerContext().getEntity(dataId);
	}	private IBEService getMgr() {
		return (IBEService)super.getBEManagerContext().getBEManager();
	}




}